package com.game.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.game.entity.player.Player;
import com.game.entity.req.PlayerSaveReqBody;
import com.game.globalconst.JsonUtil;
import com.game.globalconst.Result;
import com.game.log.dblog.RegistLog;
import com.log.service.GameLogService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class PlayerServiceImp {

	@Autowired
	private MongoTemplate playerMongoTemplate;
	@Autowired
	private GameLogService gameLogService;

	public String savePlayer(PlayerSaveReqBody playerSaveReqBody, String ip) {
		Result r = Result.build();
		String userId = playerSaveReqBody.getUserId();
		Player player;
		if (!exists(userId)) {
			player = new Player(userId,ip, playerSaveReqBody);
			log.info("自动注册玩家,userId: " + userId + " ip: " + ip);
			RegistLog dblog = new RegistLog(playerSaveReqBody.getUserId(), ip);
			gameLogService.dbExcute(dblog);
		} else {
			player = playerMongoTemplate.findById(userId, Player.class);
			r.put("Player",JsonUtil.parseToString(player.getPlayerClientData()));
		}
		log.info("玩家数据更新成功,userId:" + player.getUserId() + " ip:" + ip);
		playerMongoTemplate.save(player);
		return r.ok();
	}

	private boolean exists(String userId) {
		Query query = new Query();
		query.addCriteria(Criteria.where("userId").is(userId));
		return playerMongoTemplate.exists(query, Player.class);
	}
}
